package com.demo.glidesvgdemo;

import android.graphics.drawable.PictureDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import android.widget.TextView;
import android.os.SystemClock;

public class SvgViewHolder extends RecyclerView.ViewHolder {

    private AppCompatImageView imageView;
    private TextView loadTimeTextView;

    private boolean isFirstLoad = true; // 用于标记是否是第一次加载
    private long startTime; // 记录加载开始时间

    public SvgViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.imageView);
        loadTimeTextView = itemView.findViewById(R.id.loadTimeTextView);
    }

    public void loadSvg(int svgResourceId) {
        if (isFirstLoad) {
            // 记录加载开始时间
            startTime = System.currentTimeMillis();

            RequestBuilder<PictureDrawable> requestBuilder = Glide.with(itemView.getContext())
                    .as(PictureDrawable.class)
                    .listener(new SvgSoftwareLayerSetter())
                    .load(svgResourceId)
                    .transition(DrawableTransitionOptions.withCrossFade());

            // 添加 RequestListener 监听加载完成的时间
            requestBuilder.addListener(new RequestListener<PictureDrawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<PictureDrawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(PictureDrawable resource, Object model, Target<PictureDrawable> target, DataSource dataSource, boolean isFirstResource) {
                    // 记录加载完成时间
                    long endTime = System.currentTimeMillis();
                    long elapsedTime = endTime - startTime;

                    // 在 TextView 中显示加载时长
                    loadTimeTextView.setText("Load Time: " + elapsedTime + " ms");

                    // 标记已经加载过，避免重复加载
                    isFirstLoad = false;

                    return false;
                }
            });

            // 实际发起图片加载请求
            requestBuilder.into(imageView);
        }
    }
}





